package com.smartthinking.destinomusical.camara;

import java.util.List;

import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Size;
import android.util.Log;
import android.view.Display;
import android.view.Surface;

class CameraPreviewGingerbread implements CameraPreviewProvider {

	private int cameraId = -1;
	private int cameraOrientation;

	public Camera openCamera(int cameraId) {
		CameraInfo cameraInfo = new CameraInfo();
		this.cameraId = cameraId;
		Camera.getCameraInfo(cameraId, cameraInfo);
		cameraOrientation = cameraInfo.orientation;
		return Camera.open(cameraId);

	}

	@Override
	public void startPreview(Camera camera, int previewWidth,
			int previewHeight, Display display) {
		int displayRotation = display.getRotation();
		Camera.Parameters parameters = camera.getParameters();
		List<Size> supportedPreviewSizes = parameters
				.getSupportedPreviewSizes();
		Log.d("CameraPreview", "Rotation :" + displayRotation + ", Sizes: ");
		for (Size size : supportedPreviewSizes) {
			Log.d("CameraPreview", "Size: " + size.width + ", " + size.height);
		}
		Size optimalPreviewSize = CameraPreviewFroyo.getOptimalPreviewSize(
				supportedPreviewSizes, previewWidth, previewHeight);
		if (optimalPreviewSize != null) {
			Log.d("CameraPreview", "Optimal Size:" + optimalPreviewSize.width
					+ ", " + optimalPreviewSize.height);
			int width = optimalPreviewSize.width, height = optimalPreviewSize.height;

			int degrees = 0;
			switch (displayRotation) {
			case Surface.ROTATION_0:
				degrees = 0;
				break;
			case Surface.ROTATION_90:
				degrees = 90;
				break;
			case Surface.ROTATION_180:
				degrees = 180;
				break;
			case Surface.ROTATION_270:
				degrees = 270;
				break;
			}
			
			int result = (cameraOrientation - degrees + 360) % 360;
			
			parameters.setPreviewSize(width, height);
			
			
			CameraInfo cameraInfo = new CameraInfo();
			Camera.getCameraInfo(cameraId, cameraInfo);
			if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
				camera.setDisplayOrientation(result);
			}else{
				camera.setDisplayOrientation(90);
			}
			

			camera.setParameters(parameters);
			camera.startPreview();
		}
	}

}
